package com.feiyangedu.sample;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import java.math.BigInteger;

public class Hmac {
    public static byte[] hmac(String hmacAlgorithm, SecretKey key,  byte[] input) throws  Exception{
        Mac mac =Mac.getInstance(hmacAlgorithm);
        mac.init(key);
        mac.update(input);
        return  mac.doFinal();
    }

    public static void main(String[] args) throws  Exception {
        // http://docs.oracle.com/javase/6/docs/technotes/guides/security/StandardNames.html#Mac
        String algorithm = "HmacSHA1";
        // 原始数据:
        String data = "helloworld";
        // 随机生成一个Key:
        KeyGenerator keyGen = KeyGenerator.getInstance(algorithm);
        SecretKey skey = keyGen.generateKey();
        byte[] key = skey.getEncoded();
//        打印key
        System.out.println(String.format("%0"+ (key.length*2) + "x", new BigInteger(1, key)));
//        计算HmacSHA1
        byte[] rs = hmac(algorithm, skey, data.getBytes("UTF-8"));
        System.out.println(String.format("%0"+ (rs.length*2) + "x", new BigInteger(1, rs)));

    }
}
